package com.zjcode.cdcer.service.impl;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.entity.MPage;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.service.BaseService;
import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.component.commons.utils.StringUtils;
import com.chinatechstar.component.commons.utils.UuidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.zjcode.cdcer.mapper.CerSysteminitImportInfoMapper;
import com.zjcode.cdcer.mapper.TkmSysOrgMapper;
import com.zjcode.cdcer.mapper.TkmSysUserMapper;
import com.zjcode.cdcer.mapper.ZjcodeSelfTestInfoMapper;
import com.zjcode.cdcer.model.CerSysteminitImportInfo;
import com.zjcode.cdcer.model.TkmSysOrg;
import com.zjcode.cdcer.model.TkmSysUser;
import com.zjcode.cdcer.model.ZjcodeSelfTestInfo;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.model.excel.SelfTestTableExportVo;
import com.zjcode.cdcer.model.excel.SelfTestTableVo;
import com.zjcode.cdcer.service.CerSysteminitImportInfoService;
import com.zjcode.cdcer.service.TkmSysOrgService;
import com.zjcode.cdcer.service.ZjcodeSelfTestInfoService;
import com.zjcode.cdcer.utils.ExcelUtil;
import com.zjcode.cdcer.utils.FileUploadUtils;
import com.zjcode.cdcer.utils.IdCardValidateUtils;
import com.zjcode.cdcer.utils.Utils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.chinatechstar.component.commons.utils.StringUtils.HIGHT_STR;

/**
 * (ZjcodeSelfTestInfo)表服务实现类
 *
 * @author makejava
 * @since 2023-09-14 10:22:49
 */
@Service("zjcodeSelfTestInfoService")
public class ZjcodeSelfTestInfoServiceImpl implements ZjcodeSelfTestInfoService, BaseService {
    @Autowired
    private ZjcodeSelfTestInfoMapper zjcodeSelfTestInfoMapper;

    @Autowired
    private CerSysteminitImportInfoMapper cerSysteminitImportInfoMapper;
    @Autowired
    private CerSysteminitImportInfoService cerSysteminitImportInfoService;

    @Autowired
    private TkmSysOrgMapper sysOrgMapper;
    @Autowired
    private TkmSysOrgService tkmSysOrgService;

    @Autowired
    private TkmSysUserMapper sysUserMapper;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${studio.informed-path}")
    private String localFilePath;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ZjcodeSelfTestInfo queryById(String id) {
        return this.zjcodeSelfTestInfoMapper.queryById(id);
    }

    private Boolean checkIdCard(JSONObject jsonObject,int ageContrast) {
        String idCard = (String) jsonObject.get("idCard");
        // 先身份证的格式是否正确，再从身份证中读出年龄
        if (idCard.length()==18) {
            Integer age = IdCardValidateUtils.getPersonAgeFromIdCard(idCard);
            return age >= ageContrast;
        }
        return false;
    }


    /**
     * 判断食管癌高危条件： ① 腌晒食品 或 热汤食品 ② 持续吸烟年数 >=20年
     * @param jsonObject
     * @return
     */
    private static Boolean checkSunAndHotFood(JSONObject jsonObject) {
        // ① 腌晒食品 或 热汤食品
        if (ObjectUtils.isNotEmpty(jsonObject.get("hotFood")) && Objects.equals("3", jsonObject.get("hotFood"))) {
            return true;
        }
        return checkSmokeAndSunFood(jsonObject);
    }

    /**
     * 判断是否是高危 ： 腌晒食品 或 持续吸烟年数 >=20年
     * @param jsonObject
     * @return
     */
    private static Boolean checkSmokeAndSunFood(JSONObject jsonObject) {
        if (ObjectUtils.isNotEmpty(jsonObject.get("sunDryFood")) && Objects.equals("3", jsonObject.get("sunDryFood"))) {
            return true;
        }
        // ② 持续吸烟年数 >=20年
        return ObjectUtils.isNotEmpty(jsonObject.get("smokingYear")) && Integer.parseInt(jsonObject.get("smokingYear").toString()) >= 20;
    }

    /**
     * 判断胃癌高危条件：① 幽门螺旋杆菌感染   ② 腌晒食品 或 持续吸烟年数 >=20年 或 长期饮酒
     * @param jsonObject
     * @return
     */
    private Boolean checkGastricCancer(JSONObject jsonObject) {
        // ① 幽门螺旋杆菌感染
        if (ObjectUtils.isNotEmpty(jsonObject.get("helicobacterPyloriInfection")) && Objects.equals("2", jsonObject.get("helicobacterPyloriInfection"))) {
            return true;
        }
        // ② 腌晒食品 或 持续吸烟年数 >=20年 或 长期饮酒
        if (ObjectUtils.isNotEmpty(jsonObject.get("drink")) && Objects.equals("3", jsonObject.get("drink"))) {
            return true;
        }
        return checkSmokeAndSunFood(jsonObject);
    }


    /**
     * 一级亲属具有结直肠癌病史
     * @param zjcodeSelfTestInfo
     * @return
     */
    private static Boolean checkColorectal(ZjcodeSelfTestInfo zjcodeSelfTestInfo) {
        String colorectalCancerContent = zjcodeSelfTestInfo.getColorectalCancerContent();
        if (ObjectUtils.isNotEmpty(colorectalCancerContent)){
            JSONObject json = JSON.parseObject(colorectalCancerContent);
            return ObjectUtils.isNotEmpty(json.get("relativesHasColorectalPatients")) && Objects.equals("2", json.get("relativesHasColorectalPatients"));
        }
        return false;
    }

    /**
     * 完善高危说明
     * @param zjcodeSelfTestInfo
     */
    private void supplementalHighRisk(ZjcodeSelfTestInfo zjcodeSelfTestInfo) {
        String content = zjcodeSelfTestInfo.getContent();
        Integer highRisk = 0;
        String highRiskRemark = "";
        if (StringUtils.isNotEmpty(content)){
            JSONObject jsonObject = JSON.parseObject(content);
            String checkMirror= "";
            // 1、食管癌高危
            // 第一个条件：年龄≥45 岁
            Boolean checkIdCard = checkIdCard(jsonObject, 45);
            // 第二个条件： ① 腌晒食品 或 热汤食品 ② 持续吸烟年数 >=20年
            Boolean checkSunAndHotFood = checkSunAndHotFood(jsonObject);
            if (checkIdCard && checkSunAndHotFood){
                highRisk = 1;
                highRiskRemark ="上消化道癌";
                checkMirror = "胃镜";
            }

            // 2、胃癌高危
            // 第一个条件：年龄≥45 岁
            // 第二个条件：① 幽门螺旋杆菌感染   ② 腌晒食品 或 持续吸烟年数 >=20年 或 长期饮酒
            Boolean checkGastricCancer = checkGastricCancer(jsonObject);
            if (checkIdCard && checkGastricCancer){
                highRisk = 1;
                highRiskRemark = StringUtils.isEmpty(highRiskRemark)?"上消化道癌":highRiskRemark;
                checkMirror = org.springframework.util.StringUtils.isEmpty(checkMirror)?"胃镜":checkMirror;
            }

            // 3、结直肠癌高危（满足一个即可）
            // ① 年龄≥50岁
            Boolean checkIdCardJZC = checkIdCard(jsonObject, 50);
            // ② 一级亲属具有结直肠癌病史
            Boolean checkedColorectal = checkColorectal(zjcodeSelfTestInfo);
            if (checkIdCardJZC && checkedColorectal) {
                highRiskRemark += StringUtils.isEmpty(highRiskRemark)?"结直肠癌":"和"+"结直肠癌";
                checkMirror = StringUtils.isEmpty(checkMirror)?"肠镜":"胃、肠镜";
            }
            highRiskRemark = StringUtils.isEmpty(highRiskRemark)? "": StringUtils.format(HIGHT_STR, highRiskRemark,checkMirror);
        }
        zjcodeSelfTestInfo.setHighRisk(highRisk);
        zjcodeSelfTestInfo.setHighRiskRemark(highRiskRemark);
    }

    /**
     * 新增数据
     *
     * @param zjcodeSelfTestInfo 实例对象
     * @return 实例对象
     */
    @Override
    public JsonObj insert(ZjcodeSelfTestInfo zjcodeSelfTestInfo, PageData pageData) {
        // 完善高危说明
        supplementalHighRisk(zjcodeSelfTestInfo);
        // 查询当前记录是否已经存在
        if (zjcodeSelfTestInfo.getId() != null) {
            // 测试id为数据上报id
            String riskReportId = cerSysteminitImportInfoMapper.selRiskReportIdById(zjcodeSelfTestInfo.getId());
            if (StringUtils.isNotEmpty(riskReportId)) {
                // 进行更新
                zjcodeSelfTestInfo.setId(riskReportId);
                zjcodeSelfTestInfoMapper.update(zjcodeSelfTestInfo);
                return JsonObj.success("更新成功");
            }
        }
        if (zjcodeSelfTestInfo.getOrgId() == null) {
            TkmSysUser user = sysUserMapper.selectByPrimaryKey(Long.valueOf(pageData.get("user").toString()));
            zjcodeSelfTestInfo.setOrgId(user.getOrgId());
            zjcodeSelfTestInfo.setSource(Byte.valueOf("2"));
        }
        TkmSysOrg tkmSysOrg = sysOrgMapper.selectByPrimaryKey(zjcodeSelfTestInfo.getOrgId());
        zjcodeSelfTestInfo.setOrgName(tkmSysOrg.getOrgName());
        zjcodeSelfTestInfo.setExtFlag(findUserExtFlag(tkmSysOrg.getId()));
        zjcodeSelfTestInfo.setDelFlag(new Byte("1"));
        zjcodeSelfTestInfo.setId(UuidUtil.get32UUID());
        zjcodeSelfTestInfo.setCreateTime(new Date());
        zjcodeSelfTestInfoMapper.insert(zjcodeSelfTestInfo);
        //查询人员信息
        updatePersonnelInfoAndInitInfo(zjcodeSelfTestInfo);
        Map<String, Object> map = new HashMap<>();
        map.put("zjcodeSelfTestInfo", zjcodeSelfTestInfo);
        return JsonObj.success(map);
    }

    private void updatePersonnelInfoAndInitInfo(ZjcodeSelfTestInfo zjcodeSelfTestInfo) {
        CerSysteminitImportInfo info = zjcodeSelfTestInfoMapper.queryInfoByIdcardAnOrgId(zjcodeSelfTestInfo.getIdCard(), String.valueOf(zjcodeSelfTestInfo.getOrgId()));
        if (info != null) {
            if (info.getIsHaveError() == 1 && info.getErrorMessage().contains("风险因素自测表")) {
                //拆分错误信息
                String[] split = info.getErrorMessage().split("\\|");
                if (split.length > 1) {
                    List<String> errors = Arrays.stream(split).filter(e -> !e.contains("风险因素自测表")).collect(Collectors.toList());
                    String errormsg = errors
                            .stream()
                            .collect(Collectors.joining("|"));
                    zjcodeSelfTestInfoMapper.updateInitInfo(info.getId(), zjcodeSelfTestInfo.getId(), errormsg, null);
                } else {
                    zjcodeSelfTestInfoMapper.updateInitInfo(info.getId(), zjcodeSelfTestInfo.getId(), "", "0");
                }
            } else {
                zjcodeSelfTestInfoMapper.updateInitInfo(info.getId(), zjcodeSelfTestInfo.getId(), null, null);
            }
        }
    }

    /**
     * 修改数据
     *
     * @param zjcodeSelfTestInfo 实例对象
     * @return 实例对象
     */
    @Override
    public JsonObj update(ZjcodeSelfTestInfo zjcodeSelfTestInfo) {
        this.zjcodeSelfTestInfoMapper.update(zjcodeSelfTestInfo);
        ZjcodeSelfTestInfo info = this.queryById(zjcodeSelfTestInfo.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("info", info);
        return JsonObj.success(map);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.zjcodeSelfTestInfoMapper.deleteById(id) > 0;
    }

    @Override
    public Map<String, Object> listAllData(PageData pageData) {
        String userId = (String) pageData.get("user");
//        String extFlag = sysUserService.findUserExtFlag(userId);
        TkmSysUser userInfo = sysUserMapper.selectByPrimaryKey(Long.valueOf(userId));
        TkmSysOrg orgInfo = sysOrgMapper.selectByPrimaryKey(userInfo.getOrgId());
        pageData.put("ext_flag", orgInfo.getAncestors().replace(",", "|"));
//        pageData.put("ext_flag", extFlag);
        // 读取区域信息
        pageData = Utils.transitionRegionInfo(pageData);

        MPage mPage = getPageInfo(pageData);
        Page<Object> page = PageHelper.startPage(mPage.getCurrentPage(), mPage.getPageSize());
/*        List<LinkedHashMap<String, Object>> mapList = cerSysteminitImportInfoMapper.listAllTableData(
                pageData);*/
        List<LinkedHashMap<String, Object>> list = zjcodeSelfTestInfoMapper.listAllData(pageData);

        return PaginationBuilder.buildResult(list,
                page.getTotal(),
                mPage.getCurrentPage(),
                mPage.getPageSize());
    }

    @Override
    public String getIdByInstitutionIdAndIdCard(String institutionId, String idCard) {
        return  zjcodeSelfTestInfoMapper.queryByInstitutionIdAndIdCard(institutionId,idCard);
    }


    @Override
    public List<ZjcodeSelfTestInfo> getTestContentByIds(List<Object> contentValues) {
        return zjcodeSelfTestInfoMapper.getTestContentByIds(contentValues);
    }

    @Override
    public void exportSelfTestTable(PageData pageData, HttpServletResponse response) {
        String userId = (String) pageData.get("user");
        Object idsData = pageData.get("ids");
        List<String> ids = new ArrayList<>();
        if (idsData != null) {
            ids = Arrays.asList(String.valueOf(idsData).split("\\|"));
        }
        TkmSysUser userInfo = sysUserMapper.selectByPrimaryKey(Long.valueOf(userId));
        TkmSysOrg orgInfo = sysOrgMapper.selectByPrimaryKey(userInfo.getOrgId());
        pageData.put("idsData", idsData);
        pageData.put("ids", ids);
        pageData.put("ext_flag", orgInfo.getAncestors().replace(",", "|"));
        pageData.put("currentPage","1");
        pageData.put("pageSize","999999999");
        // 读取区域信息
        pageData = Utils.transitionRegionInfo(pageData);
        MPage mPage = getPageInfo(pageData);
        Page<Object> page = PageHelper.startPage(mPage.getCurrentPage(), mPage.getPageSize());
        List<LinkedHashMap<String, Object>> list = zjcodeSelfTestInfoMapper.listAllData(pageData);
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("查询列表为空");
        }
        Map<Long,TkmSysOrg> orgInfoMap = tkmSysOrgService.getOrgInfoMap();
        List<SelfTestTableVo> resultList=new ArrayList<>();
        list.forEach(item->{
            Object content = item.get("content");
            Object colorectalCancerContent = item.get("colorectal_cancer_content");
            SelfTestTableVo info =new SelfTestTableVo();
//            info.setUserName(ObjectUtils.isNotEmpty(item.get("user_name"))?item.get("user_name").toString():"");
//            info.setIdCard(ObjectUtils.isNotEmpty(item.get("id_card"))?item.get("id_card").toString():"");
            if (ObjectUtils.isNotEmpty(content)) {
                // 是否是高危人群（0不是 1是 ）
                String highRisk = Objects.equals("1",item.get("high_risk"))? "是" : "不是";
                info.setHighRisk(highRisk);
                info.setHighRiskRemark(ObjectUtils.isNotEmpty(item.get("high_risk_remark"))?item.get("high_risk_remark").toString():"");
                TkmSysOrg org = orgInfoMap.get(Long.valueOf(item.get("org_id").toString()));
                Gson gson = new Gson();
                JsonObject jsonObject = gson.fromJson(content.toString(), JsonObject.class);
                cerSysteminitImportInfoService.setContentSelfTestInfo(jsonObject,info,colorectalCancerContent,org);
                resultList.add(info);
            }
        });
//        ExcelUtil.writeExportEasyExcel(response,resultList,"自测表","风险因素表-自测表导出");
        try {
            ExcelUtil.setExcelResponseProp(response, "风险因素表-自测表导出");
            EasyExcel.write(response.getOutputStream())
                    .head(SelfTestTableVo.class)
                    .autoCloseStream(Boolean.FALSE)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("自测表")
                    .doWrite(resultList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void importSelfTestAgreement(MultipartFile file) {
         // 获取文件原始名称（包含后缀）
        String originalFilename = file.getOriginalFilename();
        // 文件名称（不包含后缀）
        String fileNameWithoutExtension = FilenameUtils.getBaseName(originalFilename);

        ZjcodeSelfTestInfo selfTestInfo = this.queryByIdCard(fileNameWithoutExtension);
        if (Objects.isNull(selfTestInfo)) {
            return;
        }

        try {

            String filePath = FileUploadUtils.upload(localFilePath, file);
            selfTestInfo.setInformedConsent(filePath);
            this.updateSelfTestAgreement(selfTestInfo);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ZjcodeSelfTestInfo queryByIdCard(String idCard) {
        return this.zjcodeSelfTestInfoMapper.queryByIdCard(idCard);
    }

    @Override
    public void updateSelfTestAgreement(ZjcodeSelfTestInfo info) {
        this.zjcodeSelfTestInfoMapper.updateSelfTestAgreement(info.getId(), info.getInformedConsent());

    }

    @Override
    public JsonObj importSelfTestTable(MultipartFile file, HttpServletResponse response, String userId) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        File tmpfile =cerSysteminitImportInfoService.commonImportConfig(file,userId);
        // 解析excel
        List<SelfTestTableExportVo> list = ExcelImportUtil.importExcel(tmpfile, SelfTestTableExportVo.class, params);
        // 数据过滤
        AtomicInteger count = new AtomicInteger();
        // 执行数据写入
        List<SelfTestTableExportVo> failList=new ArrayList<>();
        if(!list.isEmpty()){
            // 1、查当前登录人的机构信息
            TkmSysUser userInfo = sysUserMapper.selectByPrimaryKey(Long.valueOf(userId));
            TkmSysOrg orgInfo = sysOrgMapper.selectByPrimaryKey(userInfo.getOrgId());
            Long orgId = orgInfo.getId();
            list.forEach(item->{
                if (StringUtils.isEmpty(item.getUserName()) ) {
                    setFailImport(item, failList,"姓名不能为空",count);
                    return;
                }
                if (StringUtils.isEmpty(item.getIdCard()) ) {
                    setFailImport(item, failList,"身份证号不能为空",count);
                    return;
                }
                ZjcodeSelfTestInfo zjcodeSelfTestInfo = new ZjcodeSelfTestInfo();
                zjcodeSelfTestInfo.setUserName(item.getUserName());
                zjcodeSelfTestInfo.setIdCard(item.getIdCard());
                zjcodeSelfTestInfo.setOrgId(orgId);
                // 1）上消化道肿瘤风险因素自测表信息 封装一个json
                setJsonContent(item,zjcodeSelfTestInfo);
                // 2）结肠癌自测表信息 封装一个json
                setJsonColorectalCancerContent(item,zjcodeSelfTestInfo);
                // 2、保存数据
                saveSelfTestInfoList(item, zjcodeSelfTestInfo, orgInfo, failList, count);
            });
        }
        // 3、导出失败数据
        if(!failList.isEmpty()){
            try {
                ExcelUtil.setExcelResponseProp(response, "风险因素表-自测表导入失败");
                EasyExcel.write(response.getOutputStream())
                        .head(SelfTestTableExportVo.class)
                        .autoCloseStream(Boolean.FALSE)
                        .excelType(ExcelTypeEnum.XLSX)
                        .sheet("自测表导入失败数据")
                        .doWrite(failList);
                count.set(failList.size());
                int success = list.size() - failList.size();
                return JsonObj.success("导入成功" + success + "条 ，失败" + count + "条");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return JsonObj.success("导入成功");
    }

    private void saveSelfTestInfoList(SelfTestTableExportVo item, ZjcodeSelfTestInfo zjcodeSelfTestInfo, TkmSysOrg orgInfo,
                                      List<SelfTestTableExportVo> failList, AtomicInteger count) {
        // 2、根据当前登录人的机构、Excel表中的姓名和身份证 查询自测表信息是否存在
        ZjcodeSelfTestInfo info = zjcodeSelfTestInfoMapper.selectByInfo(zjcodeSelfTestInfo);
        if (ObjectUtils.isNotEmpty(info)) {
            // 2.1、 info 不为空
            Date createTime = info.getCreateTime();
            if (getYearDifference(createTime) > 3) {
                // 1、时间超过三年，则重新添加数据
                supplementalHighRisk(zjcodeSelfTestInfo);
                addSelfTestInfo(zjcodeSelfTestInfo, orgInfo);
            }else {
                // 2、时间未超过三年且已填写过，则更新数据
                if(ObjectUtils.isNotEmpty(info.getContent()) && ObjectUtils.isNotEmpty(info.getColorectalCancerContent())){
                    setFailImport(item, failList,"该用户三年内已经填写过自测表", count);
                    return;
                }
                if (ObjectUtils.isNotEmpty(info.getContent()) && !"{}".equals(info.getContent())){
                    // 1）上消化道肿瘤风险因素自测表信息
                    zjcodeSelfTestInfo.setContent(info.getContent());
                }
                if (ObjectUtils.isNotEmpty(info.getColorectalCancerContent()) && !"{}".equals(info.getColorectalCancerContent())){
                    // 2）存结肠癌自测表信息
                    zjcodeSelfTestInfo.setColorectalCancerContent(info.getColorectalCancerContent());
                }
                // 完善高危说明
                zjcodeSelfTestInfo.setId(info.getId());
                supplementalHighRisk(zjcodeSelfTestInfo);
                zjcodeSelfTestInfoMapper.update(zjcodeSelfTestInfo);
            }
        }else{
            // 2.2、 info 为空 : 新增数据
            supplementalHighRisk(zjcodeSelfTestInfo);
            addSelfTestInfo(zjcodeSelfTestInfo, orgInfo);
        }
        //查询并更新人员信息
        updatePersonnelInfoAndInitInfo(zjcodeSelfTestInfo);
    }

    private static void setFailImport(SelfTestTableExportVo item, List<SelfTestTableExportVo> failList,String failCause,AtomicInteger count) {
        item.setFailCause(failCause);
        failList.add(item);
        count.getAndIncrement();
    }

    /**
     * 结直肠癌风险因素自测表内容
     * @param item
     * @param zjcodeSelfTestInfo
     */
    private void setJsonColorectalCancerContent(SelfTestTableExportVo item, ZjcodeSelfTestInfo zjcodeSelfTestInfo) {
        JsonObject json = new JsonObject();
        // 1、您是否曾接受过结肠镜检查
        if(ObjectUtils.isNotEmpty(item.getIsCheck())){
            json.addProperty("isCheck", getWhether(item.getIsCheck()));
        }
        // 2、最后一次结肠镜检查的年份
        if(ObjectUtils.isNotEmpty(item.getLastCheckYear())){
            json.addProperty("lastCheckYear", item.getLastCheckYear().trim());
        }
        // 3、您是否曾接受过结肠镜检查
        if(ObjectUtils.isNotEmpty(item.getIsColorectalPolyps())){
            json.addProperty("isColorectalPolyps", getWhether(item.getIsColorectalPolyps()));
        }
        // 4、您是否曾诊断炎性肠病（IBD）
        if(ObjectUtils.isNotEmpty(item.getIsIBD())){
            json.addProperty("isIBD", getWhether(item.getIsIBD()));
        }
        // 5、诊断IBD距今时间
        if(ObjectUtils.isNotEmpty(item.getHasIBDTime())){
            json.addProperty("hasIBDTime", item.getHasIBDTime().trim());
        }else{
            if(ObjectUtils.isNotEmpty(item.getIsIBD()) && "是".equals(item.getIsIBD())){
                json.addProperty("hasIBDTime", "");
            }
        }
        // 6、您本人是否为结直肠患者
        if(ObjectUtils.isNotEmpty(item.getIsColorectalPatients())){
            json.addProperty("isColorectalPatients", getWhether(item.getIsColorectalPatients()));
        }
        // 7、您本人是否诊断有其他恶性肿瘤
        if(ObjectUtils.isNotEmpty(item.getHasOtherMalignancy())){
            json.addProperty("hasOtherMalignancy", getWhether(item.getHasOtherMalignancy()));
        }
        // 8、您的一级亲属中，是否有人患结直肠癌
        if(ObjectUtils.isNotEmpty(item.getRelativesHasColorectalPatients())){
            json.addProperty("relativesHasColorectalPatients", getWhether(item.getRelativesHasColorectalPatients()));
        }
        // 9、一级亲属中诊断肠癌的共有几人
        if(ObjectUtils.isNotEmpty(item.getRelativesHasColorectalPatientsNum())){
            json.addProperty("relativesHasColorectalPatientsNum", item.getRelativesHasColorectalPatientsNum().trim());
        }else{
            if(ObjectUtils.isNotEmpty(item.getRelativesHasColorectalPatients()) && "是".equals(item.getRelativesHasColorectalPatients())){
                json.addProperty("relativesHasColorectalPatientsNum", "");
            }
        }
        // 10、诊断肠癌的一级亲属中，诊断时最小的是几岁
        if(ObjectUtils.isNotEmpty(item.getRelativesHasColorectalPatientsMinAge())){
            json.addProperty("relativesHasColorectalPatientsMinAge", item.getRelativesHasColorectalPatientsMinAge().trim());
        }else{
            if(ObjectUtils.isNotEmpty(item.getRelativesHasColorectalPatients()) && "是".equals(item.getRelativesHasColorectalPatients())){
                json.addProperty("relativesHasColorectalPatientsMinAge", "");
            }
        }
        // 11、您是否有慢性便秘
        if(ObjectUtils.isNotEmpty(item.getHasCC())){
            json.addProperty("isConstipation", getWhether(item.getHasCC()));
        }
        // 12、您是否有慢性腹泻
        if(ObjectUtils.isNotEmpty(item.getHasCDD())){
            json.addProperty("hasCDD", getWhether(item.getHasCDD()));
        }
        // 13、您是否有粘液血便
        if(ObjectUtils.isNotEmpty(item.getMucousBloodyStool())){
            json.addProperty("mucousBloodyStool", getWhether(item.getMucousBloodyStool()));
        }
        // 14、您是否有慢性阑尾炎
        if(ObjectUtils.isNotEmpty(item.getHasChronicAppendicitis())){
            json.addProperty("hasChronicAppendicitis", getWhether(item.getHasChronicAppendicitis()));
        }
        // 15、您是否有慢性胆囊炎
        if(ObjectUtils.isNotEmpty(item.getHasChronicCholecystitis())){
            json.addProperty("hasChronicCholecystitis", getWhether(item.getHasChronicCholecystitis()));
        }
        // 16、您是否有长期遭受精神伤害
        if(ObjectUtils.isNotEmpty(item.getHasDivineDamage())){
            json.addProperty("hasDivineDamage", getWhether(item.getHasDivineDamage()));
        }
        if(ObjectUtils.isNotEmpty(json) && !json.toString().equals("{}")){
            zjcodeSelfTestInfo.setColorectalCancerContent(String.valueOf(json));
        }
    }

    private static void setJsonContent(SelfTestTableExportVo item,ZjcodeSelfTestInfo zjcodeSelfTestInfo) {
        JsonObject json = new JsonObject();
        // 【基本信息】
        // 省份
        if(ObjectUtils.isNotEmpty(item.getProvinceName())){
            json.addProperty("provinceName", item.getProvinceName().trim());
        }
        // 城市
        if(ObjectUtils.isNotEmpty(item.getCityName())){
            json.addProperty("cityName", item.getCityName().trim());
        }
        // 区县
        if(ObjectUtils.isNotEmpty(item.getDistrictName())){
            json.addProperty("districtName", item.getDistrictName().trim());
        }
        // 详细地址
        if(ObjectUtils.isNotEmpty(item.getAddress())){
            json.addProperty("address", item.getAddress().trim());
        }
        // 姓名
        if(ObjectUtils.isNotEmpty(item.getUserName())) {
            json.addProperty("userName", item.getUserName().trim());
        }
        // 身份证号
        if(ObjectUtils.isNotEmpty(item.getIdCard())) {
            json.addProperty("idCard", item.getIdCard().trim());
        }
        // 电话
        if(ObjectUtils.isNotEmpty(item.getPhone())) {
            json.addProperty("phone", item.getPhone().trim());
        }
        // 性别
        if (ObjectUtils.isNotEmpty(item.getSex())) {
            json.addProperty("sex", getSex(item.getSex()));
        }
        // "maritalStatus": "1",  婚姻状况
        if(ObjectUtils.isNotEmpty(item.getMaritalStatus())){
            json.addProperty("maritalStatus", getMaritalStatus(item.getMaritalStatus()));
        }
        // "degreeEducation": "2",  教育程度
        if(ObjectUtils.isNotEmpty(item.getDegreeEducation())){
            json.addProperty("degreeEducation", getDegreeEducation(item.getDegreeEducation()));
        }
        // "population": "3",  您家现在有几口人?（同户籍）
        if(ObjectUtils.isNotEmpty(item.getPopulation())){
            json.addProperty("population", getPopulation(item.getPopulation()));
        }
        //  "income": "4",  您家庭平均年收入大约多少元
        if(ObjectUtils.isNotEmpty(item.getIncome())){
            String income = getIncome(item.getIncome());
            json.addProperty("income", income);
        }
        //  "height": "111",  身高(cm)
        if(ObjectUtils.isNotEmpty(item.getHeight())){
            json.addProperty("height", item.getHeight().trim());
        }
        //  "weight": "43",   体重(Kg)
        if(ObjectUtils.isNotEmpty(item.getWeight())){
            json.addProperty("weight", item.getWeight().trim());
        }
        //  "systolicPressure": "2",  收缩压
        if(ObjectUtils.isNotEmpty(item.getSystolicPressure())){
            json.addProperty("systolicPressure", getSystolicPressure(item.getSystolicPressure()));
        }
        //  "diastolicPressure": "2", 舒张压
        if(ObjectUtils.isNotEmpty(item.getDiastolicPressure())){
            json.addProperty("diastolicPressure", getDiastolicPressure(item.getDiastolicPressure()));
        }
        //  【生活方式】
        //   "headwaters": "2",  饮水主要来源
        if(ObjectUtils.isNotEmpty(item.getHeadwaters())){
            json.addProperty("headwaters", getHeadwaters(item.getHeadwaters()));
        }
        //   "smoke": "2",  吸烟
        if(ObjectUtils.isNotEmpty(item.getSmoke())){
            String smoke = getSmokeWhether(item.getSmoke());
            json.addProperty("smoke", smoke);
        }
        //  "smokingFrequency": "1", 吸烟频率(支/天)
        if(ObjectUtils.isNotEmpty(item.getSmokingFrequency())){
            json.addProperty("smokingFrequency", item.getSmokingFrequency().trim());
        }
        //   "smokingYear": "1", 吸烟持续年数(年)
        if(ObjectUtils.isNotEmpty(item.getSmokingYear())){
            json.addProperty("smokingYear", item.getSmokingYear().trim());
        }
        //   "drink": "3",   饮酒
        if(ObjectUtils.isNotEmpty(item.getDrink())){
            json.addProperty("drink", getDrink(item.getDrink()));
        }
        //  "drinkQuantity":"",饮酒量
        if(ObjectUtils.isNotEmpty(item.getDrinkQuantity())){
            json.addProperty("drinkQuantity", getDrinkQuantity(item.getDrinkQuantity()));
        }
        //   "drinkFrequency":"",饮酒频率(年)
        if(ObjectUtils.isNotEmpty(item.getDrinkFrequency())){
            json.addProperty("drinkFrequency", getDrinkFrequency(item.getDrinkFrequency()));
        }
        //   "blackTea": "3",饮红茶
        if(ObjectUtils.isNotEmpty(item.getBlackTea())){
            json.addProperty("blackTea", getDrink(item.getBlackTea()));
        }
        //  "blackTeaYear":"1",饮茶持续年数
        if(ObjectUtils.isNotEmpty(item.getBlackTeaYear())){
            json.addProperty("blackTeaYear", getDuration(item.getBlackTeaYear()));
        }
        // "greenTea":"3",饮绿茶
        if(ObjectUtils.isNotEmpty(item.getGreenTea())){
            json.addProperty("greenTea", getDrink(item.getGreenTea()));
        }
        //   "greenTeaYear": "2",饮茶持续年数
        if(ObjectUtils.isNotEmpty(item.getGreenTeaYear())){
            json.addProperty("greenTeaYear", getDuration(item.getGreenTeaYear()));
        }
        //【下列食物您经常吃吗】
        //   "vegetable": "3", 新鲜蔬菜
        if(ObjectUtils.isNotEmpty(item.getVegetable())){
            json.addProperty("vegetable", getFoodWhether(item.getVegetable()));
        }
        //  "fruits": "2",   新鲜水果
        if(ObjectUtils.isNotEmpty(item.getFruits())){
            json.addProperty("fruits", getFoodWhether(item.getFruits()));
        }
        //   "eggsMilk": "3",肉蛋奶类
        if(ObjectUtils.isNotEmpty(item.getEggsMilk())){
            json.addProperty("eggsMilk", getFoodWhether(item.getEggsMilk()));
        }
        //   "BeanFood": "2",豆类食品
        if(ObjectUtils.isNotEmpty(item.getBeanFood())){
            json.addProperty("beanFood", getFoodWhether(item.getBeanFood()));
        }
        //  "sunDryFood": "2",腌晒食品
        if(ObjectUtils.isNotEmpty(item.getSunDryFood())){
            json.addProperty("sunDryFood", getFoodWhether(item.getSunDryFood()));
        }
        //   "deepFryFood": "2",油炸食品
        if(ObjectUtils.isNotEmpty(item.getDeepFryFood())){
            json.addProperty("deepFryFood", getFoodWhether(item.getDeepFryFood()));
        }
        //  "hotFood": "2",热烫食品
        if(ObjectUtils.isNotEmpty(item.getHotFood())){
            json.addProperty("hotFood", getFoodWhether(item.getHotFood()));
        }
        //   "mildewFood": "2",霉变食品
        if(ObjectUtils.isNotEmpty(item.getMildewFood())){
            json.addProperty("mildewFood", getFoodWhether(item.getMildewFood()));
        }
        //   "mealTime": "3",  您平时吃一顿饭的时间是多少分钟？
        if(ObjectUtils.isNotEmpty(item.getMealTime())){
            json.addProperty("mealTime", getMealTime(item.getMealTime()));
        }
        //   "tooth": "2", 有没有牙齿缺失
        if(ObjectUtils.isNotEmpty(item.getTooth())){
            json.addProperty("tooth", getWhether(item.getTooth()));
        }
        //  "loseTooth": "1",缺失几颗牙
        if(ObjectUtils.isNotEmpty(item.getLoseTooth())){
            json.addProperty("loseTooth", getLoseTooth(item.getLoseTooth()));
        }
        //   "plantTooth": "1",  种植/镶几颗牙
        if(ObjectUtils.isNotEmpty(item.getPlantTooth())){
            json.addProperty("plantTooth", getPlantTooth(item.getPlantTooth()));
        }
        //【消化系统疾病史】
        //   "gastroscope": "2",是否做过胃镜
        if(ObjectUtils.isNotEmpty(item.getGastroscope())){
            json.addProperty("gastroscope", getWhether(item.getGastroscope()));
        }
        //   "oesophagitis": "2",反流性食管炎
        if(ObjectUtils.isNotEmpty(item.getOesophagitis())){
            json.addProperty("oesophagitis", getWhether(item.getOesophagitis()));
        }
        //   "oesophagitisTime": "1",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getOesophagitisTime())){
            json.addProperty("oesophagitisTime", getDuration(item.getOesophagitisTime()));
        }
        //   "cardiaIntestinalMetaplasia": "2",  贲门肠上皮化生
        if(ObjectUtils.isNotEmpty(item.getCardiaIntestinalMetaplasia())){
            json.addProperty("cardiaIntestinalMetaplasia", getWhether(item.getCardiaIntestinalMetaplasia()));
        }
        //  "cardiaIntestinalMetaplasiaTime":"2",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getCardiaIntestinalMetaplasiaTime())){
            json.addProperty("cardiaIntestinalMetaplasiaTime", getDuration(item.getCardiaIntestinalMetaplasiaTime()));
        }
        //  "nonAtrophicGastritis": "2",非萎缩性胃炎
        if(ObjectUtils.isNotEmpty(item.getNonAtrophicGastritis())){
            json.addProperty("nonAtrophicGastritis", getWhether(item.getNonAtrophicGastritis()));
        }
        //  "nonAtrophicGastritisTime": "2",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getNonAtrophicGastritisTime())){
            json.addProperty("nonAtrophicGastritisTime", getDuration(item.getNonAtrophicGastritisTime()));
        }
        //   "atrophicGastritis": "2",萎缩性胃炎
        if(ObjectUtils.isNotEmpty(item.getAtrophicGastritis())){
            json.addProperty("atrophicGastritis", getWhether(item.getAtrophicGastritis()));
        }
        //   "atrophicGastritisTime": "1",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getAtrophicGastritisTime())){
            json.addProperty("atrophicGastritisTime", getDuration(item.getAtrophicGastritisTime()));
        }
        //   "intestinalMetaplasia": "2", 肠上皮化生
        if(ObjectUtils.isNotEmpty(item.getIntestinalMetaplasia())){
            json.addProperty("intestinalMetaplasia", getWhether(item.getIntestinalMetaplasia()));
        }
        //  "intestinalMetaplasiaTime": "1", 疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getIntestinalMetaplasiaTime())){
            json.addProperty("intestinalMetaplasiaTime", getDuration(item.getIntestinalMetaplasiaTime()));
        }
        //   "gastricAndDuodenalUlcers": "2", 胃、十二指肠溃疡
        if(ObjectUtils.isNotEmpty(item.getGastricAndDuodenalUlcers())){
            json.addProperty("gastricAndDuodenalUlcers", getWhether(item.getGastricAndDuodenalUlcers()));
        }
        //   "gastricAndDuodenalUlcersTime": "2", 疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getGastricAndDuodenalUlcersTime())){
            json.addProperty("gastricAndDuodenalUlcersTime", getDuration(item.getGastricAndDuodenalUlcersTime()));
        }
        //  "gastricPolyps": "1",胃息肉
        if(ObjectUtils.isNotEmpty(item.getGastricPolyps())){
            json.addProperty("gastricPolyps", getWhether(item.getGastricPolyps()));
        }
        //   "gastricPolypsTime": "1",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getGastricPolypsTime())){
            json.addProperty("gastricPolypsTime", getDuration(item.getGastricPolypsTime()));
        }
        //  "lowGradeIntraepithelialNeoplasia": "2", 低级别上皮内瘤变
        if(ObjectUtils.isNotEmpty(item.getLowGradeIntraepithelialNeoplasia())){
            json.addProperty("lowGradeIntraepithelialNeoplasia", getWhether(item.getLowGradeIntraepithelialNeoplasia()));
        }
        //   "lowGradeIntraepithelialNeoplasiaTime": "1",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getLowGradeIntraepithelialNeoplasiaTime())){
            json.addProperty("lowGradeIntraepithelialNeoplasiaTime", getDuration(item.getLowGradeIntraepithelialNeoplasiaTime()));
        }
        //  "highGradeNeoplasiaAndEarlyCancer": "2", 高级别瘤变与早癌
        if(ObjectUtils.isNotEmpty(item.getHighGradeNeoplasiaAndEarlyCancer())){
            json.addProperty("highGradeNeoplasiaAndEarlyCancer", getWhether(item.getHighGradeNeoplasiaAndEarlyCancer()));
        }
        //  "highGradeNeoplasiaAndEarlyCancerTime": "2", 疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getHighGradeNeoplasiaAndEarlyCancerTime())){
            json.addProperty("highGradeNeoplasiaAndEarlyCancerTime", getDuration(item.getHighGradeNeoplasiaAndEarlyCancerTime()));
        }
        //  "barrettEsophagus": "2",  Barrett食管（巴雷特食管）
        if(ObjectUtils.isNotEmpty(item.getBarrettEsophagus())){
            json.addProperty("barrettEsophagus", getWhether(item.getBarrettEsophagus()));
        }
        //  "barrettEsophagusTime": "2",  疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getBarrettEsophagusTime())){
            json.addProperty("barrettEsophagusTime", getDuration(item.getBarrettEsophagusTime()));
        }
        // "historyOfBenignDiseaseSubtotalGastrectomy": "2",良性疾病胃大部切除史
        if(ObjectUtils.isNotEmpty(item.getHistoryOfBenignDiseaseSubtotalGastrectomy())){
            json.addProperty("historyOfBenignDiseaseSubtotalGastrectomy", getWhether(item.getHistoryOfBenignDiseaseSubtotalGastrectomy()));
        }
        //  "historyOfBenignDiseaseSubtotalGastrectomyTime": "2",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getHistoryOfBenignDiseaseSubtotalGastrectomyTime())){
            json.addProperty("historyOfBenignDiseaseSubtotalGastrectomyTime", getDuration(item.getHistoryOfBenignDiseaseSubtotalGastrectomyTime()));
        }
        //  "historyOfSubtotalGastrectomyForGastricCancer": "2",胃癌胃大部切除史
        if(ObjectUtils.isNotEmpty(item.getHistoryOfSubtotalGastrectomyForGastricCancer())){
            json.addProperty("historyOfSubtotalGastrectomyForGastricCancer", getWhether(item.getHistoryOfSubtotalGastrectomyForGastricCancer()));
        }
        //  "historyOfSubtotalGastrectomyForGastricCancerTime": "2",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getHistoryOfSubtotalGastrectomyForGastricCancerTime())){
            json.addProperty("historyOfSubtotalGastrectomyForGastricCancerTime", getDuration(item.getHistoryOfSubtotalGastrectomyForGastricCancerTime()));
        }
        //   "gastricMucosaGiantFoldSign": "2",胃黏膜巨大皱褶征
        if(ObjectUtils.isNotEmpty(item.getGastricMucosaGiantFoldSign())){
            json.addProperty("gastricMucosaGiantFoldSign", getWhether(item.getGastricMucosaGiantFoldSign()));
        }
        //   "gastricMucosaGiantFoldSignTime": "2",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getGastricMucosaGiantFoldSignTime())){
            json.addProperty("gastricMucosaGiantFoldSignTime", getDuration(item.getGastricMucosaGiantFoldSignTime()));
        }
        //   "helicobacterPyloriInfection": "2",幽门螺杆菌感染
        if(ObjectUtils.isNotEmpty(item.getHelicobacterPyloriInfection())){
            json.addProperty("helicobacterPyloriInfection", getWhether(item.getHelicobacterPyloriInfection()));
        }
        //   "helicobacterPyloriInfectionTime": "2",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getHelicobacterPyloriInfectionTime())){
            json.addProperty("helicobacterPyloriInfectionTime", getDuration(item.getHelicobacterPyloriInfectionTime()));
        }
        //  "helicobacterPyloriDetectionMethod": "3",幽门螺杆菌检测方法
        if(ObjectUtils.isNotEmpty(item.getHelicobacterPyloriDetectionMethod())){
            json.addProperty("helicobacterPyloriDetectionMethod", getHelicobacterPyloriDetectionMethod(item.getHelicobacterPyloriDetectionMethod()));
        }
        //  "hepatitis": "2",肝炎
        if(ObjectUtils.isNotEmpty(item.getHepatitis())){
            json.addProperty("hepatitis", getWhether(item.getHepatitis()));
        }
        //   "hepatitisTime": "2",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getHepatitisTime())){
            json.addProperty("hepatitisTime", getDuration(item.getHepatitisTime()));
        }
        //"squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTract": "2",头颈部或呼吸道鳞癌
        if(ObjectUtils.isNotEmpty(item.getSquamousCellCarcinomaOfTheHeadNeckOrRespiratoryTract())){
            json.addProperty("squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTract", getWhether(item.getSquamousCellCarcinomaOfTheHeadNeckOrRespiratoryTract()));
        }
        //"squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTime": "2",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getSquamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTime())){
            json.addProperty("squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTime", getDuration(item.getSquamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTime()));
        }
        //   "perniciousAnemia": "2",恶性贫血
        if(ObjectUtils.isNotEmpty(item.getPerniciousAnemia())){
            json.addProperty("perniciousAnemia", getWhether(item.getPerniciousAnemia()));
        }
        //   "perniciousAnemiaTime": "2",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getPerniciousAnemiaTime())){
            json.addProperty("perniciousAnemiaTime", getDuration(item.getPerniciousAnemiaTime()));
        }
        //   "else": "2", 其它
        if(ObjectUtils.isNotEmpty(item.getElseStr())){
            json.addProperty("else", getWhether(item.getElseStr()));
        }
        //   "diseasName": "22",疾病名称
        if(ObjectUtils.isNotEmpty(item.getDiseasName())){
            json.addProperty("diseasName", item.getDiseasName().trim());
        }
        //   "elseTime": "1",疾病确诊后时间
        if(ObjectUtils.isNotEmpty(item.getElseTime())){
            json.addProperty("elseTime", getDuration(item.getElseTime()));
        }
        //  "firstDegreeRelativeHadTumor": "1", 肿瘤家族史  -  你家中有没有人得过肿瘤
        if(ObjectUtils.isNotEmpty(item.getFirstDegreeRelativeHadTumor())){
            json.addProperty("firstDegreeRelativeHadTumor", getWhether(item.getFirstDegreeRelativeHadTumor()));
        }
        /*
          家中得过肿瘤-亲属关系
          封装的json格式
          "content":[
          {"firstDegreeRelativeHadTumor":"","domesticRelation":"2","tumorName":"7","elseName":""},
          {"firstDegreeRelativeHadTumor":"","domesticRelation":"3","tumorName":"6","elseName":""},
          {"firstDegreeRelativeHadTumor":"","domesticRelation":"1","tumorName":"2","elseName":""}
          ]
          domesticRelation:亲属关系
          tumorName：肿瘤情况
         */
        if(ObjectUtils.isNotEmpty(item.getDomesticRelationHadTumor())){
            JsonArray contentArray = new JsonArray();
            String[] domesticRelationHadTumorArray = item.getDomesticRelationHadTumor().split("\\|");
            for (String domesticRelationHadTumor : domesticRelationHadTumorArray) {
                String[] domesticRelationHadTumorKeyValue = domesticRelationHadTumor.split("：");
                if (domesticRelationHadTumorKeyValue.length == 2) {
                    JsonObject jsonObject = new JsonObject();
                    String domesticRelation = domesticRelationHadTumorKeyValue[0].trim();
                    String tumorName = domesticRelationHadTumorKeyValue[1].trim();
                    jsonObject.addProperty("domesticRelation", getDomesticRelation(domesticRelation));
                    jsonObject.addProperty("tumorName", getTumorName(tumorName));
                    contentArray.add(jsonObject);
                }
            }
//            json.addProperty("content", String.valueOf(contentArray));
            json.add("content", contentArray);
        }
        if(ObjectUtils.isNotEmpty(json) && !json.toString().equals("{}")) {
            zjcodeSelfTestInfo.setContent(String.valueOf(json));
        }

    }

    private static String getTumorName(String tumorName) {
        String value = "";
        if (ObjectUtils.isNotEmpty(tumorName)){
            switch (tumorName){
                case "肺癌":
                    value = "1";
                    break;
                case "乳腺癌":
                    value = "2";
                    break;
                case "结直肠癌":
                    value = "3";
                    break;
                case "肝癌":
                    value = "4";
                    break;
                case "胃癌":
                    value = "5";
                    break;
                case "食管癌":
                    value = "6";
                    break;
                case "子宫颈癌":
                    value = "7";
                    break;
                case "甲状腺癌":
                    value = "8";
                    break;
                case "前列腺癌":
                    value = "9";
                    break;
                case "子宫体癌":
                    value = "10";
                    break;
                case "口腔和咽喉肿瘤":
                    value = "11";
                    break;
                case "鼻咽癌":
                    value = "12";
                    break;
                case "肛门癌":
                    value = "13";
                    break;
                case "胆囊癌":
                    value = "14";
                    break;
                case "胰腺癌":
                    value = "15";
                    break;
                case "喉癌":
                    value = "16";
                    break;
                case "骨肿瘤":
                    value = "17";
                    break;
                case "皮肤黑色素瘤":
                    value = "18";
                    break;
                case "卵巢癌":
                    value = "19";
                    break;
                case "睾丸癌":
                    value = "20";
                    break;
                case "肾癌":
                    value = "21";
                    break;
                case "膀胱癌":
                    value = "22";
                    break;
                case "脑和中枢神经系统肿瘤":
                    value = "23";
                    break;
                case "淋巴瘤":
                    value = "24";
                    break;
                case "白血病":
                    value = "25";
                    break;
                case "其他":
                    value = "26";
                    break;
            }
        }
        return value;
    }

    private static String getDomesticRelation(String domesticRelation) {
        String value= "";
        if (ObjectUtils.isNotEmpty(domesticRelation)) {
            switch (domesticRelation){
                case "父母":
                    value = "1";
                    break;
                case "兄弟姐妹":
                    value = "2";
                    break;
                case "儿女":
                    value = "3";
                    break;
            }
        }
        return value;
    }

    private static String getMealTime(String mealTime) {
        switch (mealTime.trim()){
            case "1 ~ 10分钟":
                return "1";
            case "11 ~ 20分钟":
                return "2";
            case "21 ~ 30分钟":
                return "3";
            case "30分钟以上":
                return "4";
            default:
                return "";
        }
    }

    private static String getHelicobacterPyloriDetectionMethod(String helicobacterPyloriDetectionMethod) {
        switch (helicobacterPyloriDetectionMethod.trim()) {
            case "快速尿素酶试验":
                return "1";
            case "碳 13呼气试验":
                return "2";
            case "碳 14呼气试验":
                return "3";
            case "血清抗体试验":
                return "4";
            case "病理诊断":
                return "5";
            case "粪便抗原检测":
                return "6";
            case "不清楚":
                return "7";
            default:
                return "";
        }
    }

    private static String getPlantTooth(String plantTooth) {
        switch (plantTooth.trim()) {
            case "无":
                return "1";
            case "1颗":
                return "2";
            case "2 ~ 4颗":
                return "3";
            case "3 ~ 5颗":
                return "4";
            case "5颗以上":
                return "5";
            default:
                return "";
        }
    }

    private static String getLoseTooth(String loseTooth) {
        switch (loseTooth.trim()) {
            case "1颗":
                return "1";
            case "2 ~ 4颗":
                return "2";
            case "3 ~ 5颗":
                return "3";
            case "5颗以上":
                return "4";
            default:
                return "";
        }
    }

    private static String getIncome(String item) {
        switch (item.trim()) {
            case "1万以下":
                return "1";
            case "1 ~ 4.9万":
                return "2";
            case "5 ~ 9.9万":
                return "3";
            case "10 ~ 19.9万":
                return "4";
            case "20万以上":
                return "5";
            default:
                return "";
        }
    }

    private static String getPopulation(String item) {
        String population = "";
        switch (item.trim()) {
            case "1人":
                population = "1";
                break;
            case "2 ~ 3人":
                population = "2";
                break;
            case "4 ~ 5人":
                population = "3";
                break;
            case "6 ~ 7人":
                population = "4";
                break;
            case "8 ~ 9人":
                population = "5";
                break;
            case "10人及以上":
                population = "6";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return population;
    }

    private static String getDegreeEducation(String item) {
        String degreeEducation = "";
        switch (item.trim()) {
            case "未上过学":
                degreeEducation = "1";
                break;
            case "小学":
                degreeEducation = "2";
                break;
            case "初中":
                degreeEducation = "3";
                break;
            case "高中":
                degreeEducation = "4";
                break;
            case "大专及以上":
                degreeEducation = "5";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return degreeEducation;
    }

    private static String getMaritalStatus(String item) {
        String maritalStatus = "";
        switch (item.trim()) {
            case "未婚":
                maritalStatus = "1";
                break;
            case "已婚":
                maritalStatus = "2";
                break;
            case "离异":
                maritalStatus = "3";
                break;
            case "丧偶":
                maritalStatus = "4";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return maritalStatus;
    }

    private static String getSex(String item) {
        String sex = "";
        switch (item.trim()){
            case "男":
                sex = "1";
                break;
            case "女":
                sex = "2";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return sex;
    }

    private static String getSystolicPressure(String item) {
        String systolicPressure="";
        switch (item.trim()) {
            case "120mmHg以下":
                systolicPressure = "1";
                break;
            case "120mmHg ~ 139mmHg":
                systolicPressure = "2";
                break;
            case "140mmHg ~ 179mmHg":
                systolicPressure = "3";
                break;
            case "180mmHg以上":
                systolicPressure = "4";
                break;
            default:
                break;
        }
        return systolicPressure;
    }

    private static String getDiastolicPressure(String item) {
        String diastolicPressure="";
        switch (item.trim()) {
            case "80mmHg以下":
                diastolicPressure = "1";
                break;
            case "80mmHg ~ 89mmHg":
                diastolicPressure = "2";
                break;
            case "90mmHg ~ 109mmHg":
                diastolicPressure = "3";
                break;
            case "110mmHg以上":
                diastolicPressure = "4";
                break;
        }
        return diastolicPressure;
    }

    private static String getHeadwaters(String item) {
        String headwaters="";
        switch (item.trim()) {
            case "地窖水、池塘水、浅井水":
                headwaters = "1";
                break;
            case "湖水、河水":
                headwaters = "2";
                break;
            case "深井水、泉水":
                headwaters = "3";
                break;
            case "纯净水/自来水(经处理)":
                headwaters = "4";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return headwaters;
    }

    private static String getSmokeWhether(String item) {
        String smoke="";
        switch (item.trim()) {
            case "是":
                smoke = "1";
                break;
            case "否":
                smoke = "2";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return smoke;
    }

    private static String getDrinkQuantity(String item) {
        String drinkQuantity = "";
        switch (item.trim()) {
            case "<2两":
                drinkQuantity = "1";
                break;
            case "2 ~ 5两":
                drinkQuantity = "2";
                break;
            case "6 ~ 10两":
                drinkQuantity = "3";
                break;
            case ">10两":
                drinkQuantity = "4";
                break;
            default:
                break;
        }
        return drinkQuantity;
    }

    private static String getDrinkFrequency(String item) {
        String drinkFrequency = "";
        switch (item.trim()) {
            case "一周2 ~ 3次":
                drinkFrequency = "1";
                break;
            case "一周4 ~ 6次":
                drinkFrequency = "2";
                break;
            case "一周6次以上":
                drinkFrequency = "3";
                break;
            default:
                break;
        }
        return drinkFrequency;
    }

    private static String getWhether(String str) {
        String whether="";
        switch (str.trim()) {
            case "是":
                whether = "1";
                break;
            case "否":
                whether = "2";
                break;
            case "不清楚":
                whether = "3";
                break;
            default:
                // 处理其他未知情况
        }
        return whether;
    }

    private static String getFoodWhether(String vegetable) {
        String vegetableWhether="";
        switch (vegetable.trim()) {
            case "从不":
                vegetableWhether = "1";
                break;
            case "很少(<2次/周)":
                vegetableWhether = "2";
                break;
            case "经常(>=2次/周)":
                vegetableWhether = "3";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return vegetableWhether;
    }

    private static String getDuration(String blackTeaYear) {
        String duration="";
        switch (blackTeaYear.trim()) {
            case "<1年":
                duration = "1";
                break;
            case "1 ~ 5年":
                duration = "2";
                break;
            case "6 ~ 10年":
                duration = "3";
                break;
            case ">10年":
                duration = "4";
                break;
            default:
                break;
        }
        return duration;
    }

    private static String getDrink(String obj) {
        String drink="";
        switch (obj.trim()) {
            case "不喝":
                drink = "1";
                break;
            case "偶尔喝":
                drink = "2";
                break;
            case "经常喝":
                drink = "3";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return drink;
    }

    private void addSelfTestInfo(ZjcodeSelfTestInfo zjcodeSelfTestInfo, TkmSysOrg orgInfo) {
        // 1、时间超过三年,可重新进行问卷填写, 即重新生成一条数据
        String id = UuidUtil.get32UUID();
        zjcodeSelfTestInfo.setId(id);
        zjcodeSelfTestInfo.setSource(new Byte("1"));
        zjcodeSelfTestInfo.setOrgName(orgInfo.getOrgName());
        zjcodeSelfTestInfo.setCreateTime(new Date());
        zjcodeSelfTestInfo.setDelFlag(new Byte("1"));
        zjcodeSelfTestInfo.setExtFlag(findUserExtFlag(orgInfo.getId()));
        zjcodeSelfTestInfoMapper.insert(zjcodeSelfTestInfo);
    }

    /**
     * 计算两个日期之间的年差
     * @param time 时间
     * @return 年差
     */
    public static int getYearDifference(Date time) {
        // 将Date转换为LocalDate以进行日期操作
        LocalDate createLocalDate = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 获取当前日期
        LocalDate now = LocalDate.now();
        // 计算两个日期之间的年差
        return createLocalDate.until(now).getYears();
    }


    private String findUserExtFlag(Long orgId) {
        // 机构编号
        TkmSysOrg org = sysOrgMapper.selectByPrimaryKey(orgId);
        // 获取当前机构的详情
        String ancestors = org.getAncestors();
        List<String> list = new ArrayList<>();
        if (!StringUtils.isEmpty(ancestors)) {
            list.addAll(Arrays.asList(ancestors.split(",")));
        }
        list.add(orgId.toString());
        String extFlag = list
                .stream()
                .collect(Collectors.joining("|"));
        return extFlag;
    }
}
